package com.jt.service;

import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    /**
     *业务思维能力: 用户登录操作
     * 登录业务逻辑:
     *      1.将用户的密码进行加密处理
     *      2.根据用户名和密码进行数据库查询
     *          查到了: 用户名和密码正确 返回token秘钥
     *          没查到: 用户名和密码错误 返回null
     *
     */
    @Override
    public String login(User user) {
        //1.将密码加密处理
        String password = user.getPassword();
        String md5Pass = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(md5Pass);
        //2.根据用户名和密码查询数据库
        User userDB = userMapper.findUserByUP(user);
        if (userDB == null){
            //用户名或者密码错误
            return null;
        }
        //秘钥:该秘钥是用户登录的唯一的标识符,特点:独一无二
        String token = UUID.randomUUID().toString()
                .replace("-", "");

        return token;
    }

    @Override
    public PageResult findList(PageResult pageResult) {
        //1.获取记录总数
        long total = userMapper.findCount();
        //2.获取分页结果
        int size = pageResult.getPageSize(); //条数
        int start = (pageResult.getPageNum() -1) * size; //起始位置
        String query = pageResult.getQuery(); //查询条件
        //查询分页结果
        List<User> list = userMapper.findUserLimit(query,start,size);
        //封装返回数据
        pageResult.setTotal(total).setRows(list);
        return pageResult;
    }

    @Override
    @Transactional //控制事物
    public void updateStatus(User user) {
        //获取当前时间
        user.setUpdated(new Date());
        userMapper.updateStatus(user);
    }

    @Override
    @Transactional
    public void deleteUserById(Integer id) {
        userMapper.deleteUserById(id);
    }

    @Override
    public void addUser(User user) {
        //1.密码加密
        Date date = new Date();
        String md5Pass = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Pass).setStatus(true).setCreated(date).setUpdated(date);
        userMapper.addUser();
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.findUserById(id);
    }

    //电话/邮箱/更新时间/ where id = xx
    @Override
    @Transactional
    public void updateUser(User user) {
        user.setUpdated(new Date());
        userMapper.updateUser(user);

//        System.out.println(1/0);  //故意暴露错误,学习错误处理
    }
}
